import React from 'react';
import { connect } from 'dva';
import { Link,browserHistory,History } from 'dva/router';
import { Drawer, List, NavBar,Icon, InputItem ,Picker, TabBar,Pagination ,Toast ,Button,NoticeBar,} from 'antd-mobile';
import { createForm } from 'rc-form'
import style from '../../style/App.less'
import Reset from '../../style/ResetInput.less'
import NavStyle from '../../style/ResNav.less'
import reqwest from 'reqwest';
import PropTypes from 'prop-types'
import {numvail} from '../../utils/Validator.js'
class AppLogin extends React.Component{
	constructor(props){
		super(props);
		this.state={
      phone:undefined,
      password:undefined
		}
	}
	loadServer(data={}){
    let _this =this;
		console.log(data)
    if(window.sessionStorage['wechat']==undefined){

    }
		reqwest({
      url: window.host+'/api/sessions',
      method: 'post',
      crossOrigin: true,
      type: 'json',
      data:{login:data.phone.replace(/\s+/g, ""),password:data.password,open_id:window.sessionStorage['wechat'],wx_access_token:window.localStorage['wechat_token']},
    }).then((data) => {
      if(data.status=='success'){
        let set ={"mobile":data.current_user.mobile,"avatar":data.current_user.avatar,"avatar_url":data.current_user.avatar_url,"name":data.current_user.name,"role":data.current_user.role,
        "accout_name":data.current_user.account.name,"accout_address":data.current_user.account.address,"invit_url":data.current_user.account.invit_url}
          Toast.success(
          '登录成功',
          1,
          ()=>{
            window.localStorage['token']=data.token;
              window.localStorage['curloe']=data.current_user.role;
              // debugger
              window.localStorage['menu']=JSON.stringify(data.menu);
              window.localStorage['cgj_id']=data.current_user.cgj_user_id;
              window.localStorage['account_type']=data.current_user.account_type;
              window.localStorage['userrr_id']=data.current_user.id;
              window.localStorage['setting']=JSON.stringify(set);
              window.localStorage['money'] = JSON.stringify(data.current_user.wallet)
              // window.sessionStorage['companies']=JSON.stringify(data.companies);
              window.localStorage['material']=JSON.stringify(data.materials); 
              // window.sessionStorage['store_tree']=JSON.stringify(data.stores_tree);
               window.sessionStorage['surveyors']=JSON.stringify(data.surveyors);
              // window.location.hash=window.location.hash
              // window.sessionStorage.removeItem('wechat')
              // window.location.hash='/hfive/home';
              // _this.props.history.push(null,'/hfive/home')
              _this.context.router.replace('/hfive/home')
              // _this.props.history.replaceState(null, 'logs')}
              // _this.props.history.goBack();

              // browserHistory.push('#/hfive/home')
          }
        )
        
      }else{
        Toast.fail(
          data.msg,
          1
        )
      }
    }).fail( (err, msg) =>{
       Toast.offline('网络连接失败!!!', 1);
    });
	}
	handleSubmit(e){
		e.preventDefault();
    let _this =this;

    this.props.form.validateFields((err, values) => {
      console.log(values);
      if (!err) {
        this.loadServer({phone:values.phone,password:values.password})
      }
    });
	}
  componentWillMount(){
    // console.log(this)
    // this.context.router.replace('/hfive/home')
    // this.props.dispatch({type:'hfive/home'})
    // this.props.location.pathname='/hfive/home'
    window.localStorage.clear()
    let c =window.location.href;
    let _this = this;
    let _uri= encodeURIComponent('http://mobile.salesgj.com/#/log');
    let uri ='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1211e96e6c279899&redirect_uri='+_uri+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
    // let uri ='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaaedf3a1c23da5c0&redirect_uri=https://api.chuanggj.com&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
    // alert(uri);
    this.setState({uri})
    
    // alert(navigator)
    if(c.match(/code/)==['code']||c.match(/code/)=="code"){
      let a =window.location.href.match(/code\=\w+/);
      let b = a[0].match(/\w+/g);
      reqwest({
        url: window.host+'/api/wechat/auth',
        method: 'post',
        crossOrigin: true,
        data:{
          code:b[1]
        },
        type: 'json',
      }).then((data)=>{
        if(data.code==200){
          window.sessionStorage['wechat']=data.result.openid;
          window.localStorage['wechat_token']=data.result.access_token
        }
      }).fail((data)=>{
         console.log(data);
      })

     // reqwest({
     //    url: 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1211e96e6c279899&secret=92638679efd96e9033fcbecf62eed460&code='+b[1]+'&grant_type=authorization_code',
     //    method: 'get',
     //    crossOrigin: true,
     //    type: 'json',
     //  }).then((data)=>{
     //    console.log(data);
     //  }).fail((data)=>{
     //     console.log(data);
     //  })
    }
   
    // alert(window.location)
  }
	render(){
    let _this = this;
		 const { getFieldProps,getFieldError } = this.props.form;
		 return(
			<div>
				<NavBar style={{height:'1rem',background:'#3dbd7d'}} className={`${NavStyle.tel_nav}`}  iconName={false} leftContent={<Link className={`${style.white}`} to={{pathname:''}}><Icon type="left"  style={{marginBottom:'-0.1rem',}}  />返回首页</Link>}  onLeftClick={()=>{console.log(1)}} >登录</NavBar>
        <NoticeBar  marqueeProps={{ loop: true, style: { padding: '0 0.15rem' } }} mode="closable" icon={null}>第一次登录微信授权后需要输入手机号与密码进行绑定</NoticeBar>
				<h1 style={{textAlign:'center'}}>管家快销</h1>
				<List >
          <InputItem
          clear={true}
          className={`${Reset.tel_input}`}
            {...getFieldProps('phone',{
              // initialValue:'请输入你的手机号码',
              rules:[{required:true,message:'请输入手机号',validator:(rule,value,callback)=>{
                !!value?numvail(rule,value.replace(/\s+/g, ""),callback):callback('请输入手机号码')
              }}]
            })}
            
            error={!!getFieldError('phone')}
            onErrorClick={() => {
              alert(getFieldError('phone').join('、'));
            }}
            type="phone"  placeholder="手机号码"
          >手机号码</InputItem>
          <InputItem
          clear={true}
            className={`${Reset.tel_input}`}
            {...getFieldProps('password',{
              // initialValue:this.state.password,
              rules:[{required:true,message:'请输入密码'}]
            })}
            error={!!getFieldError('password')}
            onErrorClick={() => {
              alert(getFieldError('password').join('、'));
            }}
            type="password"
            
          >密码</InputItem>
        </List>
        <Button className={`${Reset.btn_moblie} ${Reset.tel_btn}`} onClick={this.handleSubmit.bind(this)}  type='primary'>点击登录</Button>
        <div style={{textAlign:'center',fontSize:'0.3rem'}}><a href={this.state.uri}>微信登录</a> <Link to={{pathname:'/reg'}}>注册</Link></div>
        
			</div>
	 	)
		
	}
}
const AppLoginForm = createForm()(AppLogin);

AppLogin.contextTypes = {
  router: PropTypes.object
};
export default connect()(AppLoginForm)